<script lang="tsx" setup>
import { reactive, ref, watch } from 'vue';
import type { FormRules, StepsProps } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import type { PackageVO, TenantVO } from '@/service/types/tenant';
import { getPackageList } from '@/service/api/tenants/package';
import { addTenant } from '@/service/api/tenants/tenant';
type Model = Pick<
  TenantVO,
  | 'status'
  | 'companyName'
  | 'licenseNumber'
  | 'address'
  | 'domain'
  | 'intro'
  | 'password'
  | 'packageId'
  | 'expireTime'
  | 'remark'
  | 'accountCount'
  | 'contactPhone'
  | 'username'
  | 'contactUserName'
>;
const loading = ref(false);
interface Emits {
  (e: 'submitted'): void;
}
const visible = defineModel<boolean>('visible', {
  default: false
});
function closeAddModal() {
  visible.value = false;
}
const current = ref<number | null>(1);
const emit = defineEmits<Emits>();
const packageOptions = ref<PackageVO[]>([]);
defineOptions({
  name: 'ClientForm'
});
const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();
const rules: FormRules = {
  companyName: [
    {
      required: true,
      message: '公司名称不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 50,
      message: '公司名称不得超过20个字符',
      trigger: 'blur'
    }
  ],
  contactUserName: [
    {
      required: true,
      message: '联系人不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '联系人不得超过20个字符',
      trigger: 'blur'
    }
  ],
  contactPhone: [
    {
      required: true,
      message: '联系电话不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '联系电话不得超过20个字符',
      trigger: 'blur'
    }
  ],
  username: [
    {
      required: true,
      message: '账号不能为空',
      trigger: 'blur'
    },
    {
      required: true,
      min: 2,
      max: 20,
      message: '用户名称长度必须介于 2 和 20 之间',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur'
    },
    {
      pattern: /^(?=.*[A-Z])(?=.*[@$!%*?&.])[A-Za-z\d@$!%*?&.]{8,}$/,
      message: '长度最少8为，至少包含一个大写加特殊字符',
      trigger: 'blur'
    }
  ],
  packageId: createRequiredRule('请选择套餐'),
  intro: {
    required: false,
    min: 0,
    max: 180,
    message: '企业简介不得超出180个字符',
    trigger: 'blur'
  },
  address: {
    required: false,
    min: 0,
    max: 180,
    message: '企业地址不得超出180个字符',
    trigger: 'blur'
  },
  licenseNumber: {
    required: false,
    min: 0,
    max: 30,
    message: '统一社会信用代码不得超出30个字符',
    trigger: 'blur'
  },
  domain: {
    required: false,
    min: 0,
    max: 200,
    message: '域名不得超出200个字符',
    trigger: 'blur'
  }
};

const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    status: '0',
    companyName: '',
    licenseNumber: '',
    packageId: null,
    username: '',
    password: '',
    contactPhone: '',
    domain: '',
    intro: '',
    address: '',
    expireTime: null,
    contactUserName: '',
    accountCount: -1
  };
}

const handleInitModel = async () => {
  Object.assign(model, createDefaultModel());
};
const getPackages = async () => {
  const { error, data } = await getPackageList();
  if (!error) {
    console.log(data);
    // @ts-expect-error 忽略request返回数据的错误
    packageOptions.value = data?.data;
  }
};
const handleReset = async () => {
  current.value = 1;
};
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    getPackages();
    handleReset();
    restoreValidation();
  }
});

const currentStatus = ref<StepsProps['status']>('process');
const handleSubmit = async () => {
  loading.value = true;
  const { ...params } = model;
  const { error, data } = await addTenant(params as TenantVO);
  loading.value = false;
  if (!error) {
    // @ts-expect-error 忽略request返回数据的错误
    (window as any).$message?.success(data?.msg);
    emit('submitted');
    closeAddModal();
  }
};
const nextStep = async () => {
  await validate();
  if (current.value === null) current.value = 1;
  else if (current.value >= 3) {
    handleSubmit();
  }
  // eslint-disable-next-line no-plusplus
  else current.value++;
};
const prevStep = () => {
  if (current.value === 1) current.value = 1;
  else if (current.value === null) current.value = 3;
  // eslint-disable-next-line no-plusplus
  else current.value--;
};
const shortcuts = reactive({
  永久: 4131619200000
});
</script>

<template>
  <NModal v-model:show="visible" title="创建租户" preset="card" class="w-800px">
    <NForm ref="formRef" :model="model" :rules="rules">
      <NSteps :current="current as number" :status="currentStatus">
        <NStep title="公司基本信息" />
        <NStep title="管理员信息" />
        <NStep title="套餐信息" />
        <!-- <NStep title="结果" /> -->
      </NSteps>
      <div class="mt-20px">
        <div v-if="current == 1">
          <NGrid x-gap="12" responsive="screen" item-responsive>
            <NFormItemGi span="24 s:12 m:12" label="公司名称" path="companyName">
              <NInput v-model:value="model.companyName" placeholder="请输入公司名称" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="联系人" path="contactUserName">
              <NInput v-model:value="model.contactUserName" placeholder="请输入联系人" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="联系电话" path="contactPhone">
              <NInput v-model:value="model.contactPhone" placeholder="请输入联系电话" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="社会信用代码" path="licenseNumber">
              <NInput v-model:value="model.licenseNumber" placeholder="请输入统一社会信用代码" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="企业地址" path="address">
              <NInput
                v-model:value="model.address"
                :autosize="{
                  minRows: 3,
                  maxRows: 5
                }"
                :maxlength="180"
                show-count
                type="textarea"
                placeholder="请输入企业地址"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="企业简介" path="intro">
              <NInput
                v-model:value="model.intro"
                :autosize="{
                  minRows: 3,
                  maxRows: 5
                }"
                :maxlength="180"
                show-count
                type="textarea"
                placeholder="请输入企业简介"
              />
            </NFormItemGi>
          </NGrid>
        </div>
        <div v-else-if="current == 2">
          <NGrid x-gap="12" responsive="screen" item-responsive>
            <NFormItemGi span="24 s:12 m:12" label="管理员账号" path="username">
              <NInput v-model:value="model.username" placeholder="请输入公司名称" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="管理员密码" path="password">
              <NInput
                v-model:value="model.password"
                show-password-on="mousedown"
                type="password"
                placeholder="请输入管理员密码"
              />
            </NFormItemGi>
          </NGrid>
        </div>
        <div v-else-if="current == 3">
          <NGrid x-gap="12" responsive="screen" item-responsive>
            <NFormItemGi span="24 s:12 m:12" label="套餐信息" path="packageId">
              <NSelect
                v-model:value="model.packageId"
                :options="packageOptions"
                value-field="packageId"
                filterable
                label-field="packageName"
                clearable
                placeholder="请选择套餐信息"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="过期时间" path="expireTime">
              <NDatePicker
                v-model:value="model.expireTime"
                :shortcuts="shortcuts"
                class="w-100%"
                clearable
                placeholder="请选择过期时间"
              />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="账号数量" path="accountCount">
              <NInputNumber
                v-model:value="model.accountCount"
                class="w-100%"
                clearable
                placeholder="请输入账号最大数量"
              />
              <template #label>
                <FormLabelExtends label="账号数量" tips="-1代表不限制" />
              </template>
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:12" label="绑定域名" path="domain">
              <NInput v-model:value="model.domain" placeholder="请输入绑定域名" />
            </NFormItemGi>
          </NGrid>
        </div>
      </div>
    </NForm>
    <template #footer>
      <NSpace justify="end">
        <NButton @click="closeAddModal">取消</NButton>
        <NButton v-if="current !== null || current !== 1" @click="prevStep">上一步</NButton>
        <NButton type="primary" :loading="loading" @click="nextStep">
          {{ current as number >= 3 ? '提交' : '下一步' }}
        </NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped></style>
